/*
 * @Author: your name
 * @Date: 2021-07-09 16:08:18
 * @LastEditTime: 2021-07-12 16:01:55
 * @Description: 路由权限
 */
import router, { constantRoutes, asyncRoutes } from '@/router/index'

/**
 * @description: 筛选有权限的路由
 * @param {*}
 * @return {*}
 */
const filterAsyncRoutes = (routes, powerList) => {
  const res = []
  for (const route of routes) {
    for (const power of powerList) {
      if (route.path === power.url) {
        if (route.children) {
          // 如果路由有子级，筛选子级
          route.children = filterAsyncRoutes(route.children, powerList)
        }
        res.push(route)
      }
    }
  }
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  REMOVE_ROUTES: state => {
    state.addRoutes = []
    state.routes = []
  },
  setRoutes: (state, routes) => {
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, powerList) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, powerList)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  getPermissonRoutes({ commit }) {
    // api request
    const accessedRoutes = asyncRoutes
    // 动态添加路由  vue-router4.x 暂时没有addRoutes
    // eslint-disable-next-line no-restricted-syntax
    for (const item of accessedRoutes) {
      router.addRoute(item)
    }
    router.options.routes = constantRoutes.concat(asyncRoutes)
    commit('setRoutes', accessedRoutes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
